<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ include file="blocks/header.jsp" %>
<%@ include file="dialogs/newRealtyDialogs.jsp" %>
<%@ include file="dialogs/addPhotoDialog.jsp" %>

<script type="text/javascript">
    $(function(){
        
        var AnnouncementsController = Backbone.Router.extend({
            routes: {
                "deleteAnnouncement/:id": "deleteAnnouncement",
                "editAnnouncement/:id": "editAnnouncement"
            },
            deleteAnnouncement: function(id) {
                var self = this;
                $.dialog("dialogDeleteAnnouncement", {
                    title: "Удаление объявления",
                    body: "Вы уверены что хотите удалить объявление?",
                    active_button: "Ok",
                    buttons: {
                        "Ok": function() {
                            $.dialog("dialogDeleteAnnouncement", "close");
                            announcementsCollection.deleteAnnouncement(id);
                        },
                        "Отмена": function() {
                            $.dialog("dialogDeleteAnnouncement", "close");
                        }
                    }
                });
                self.navigate("", {trigger: false, replace: true});
                
            },
            editAnnouncement: function(id) {
                this.navigate("", {trigger: false, replace: true});
            }
        });
        
        
        var Realty = Backbone.Model.extend({            
            defaults:{"id":3,
                          "type":"",
                          "description":"",
                          "adress":"Днепропетровск ул. Апостоловская 98",
                          "level":5,
                          "levelsBuilding":5,
                          "numberRooms":1,
                          "area":566.0
                      }
        });
        
        var Announcement = Backbone.Model.extend({
            defaults:{"id":2,
                      "price":5666.0,
                      "operation":"SALE",
                      "status":true,
                      "datePublication":1359920680000
            }  
        });
        
        var AnnouncementsCollection = Backbone.Collection.extend({
            model: Announcement,
            newRealtyModel: newRealtyModel,
            initialize: function(){
                this.newRealtyModel.bind("saveToServer", this.loadData, this);
                this.loadData();
            },
            _getModel: function(inJson) {
                var realty = new Realty(inJson['realty']);
                inJson['realty'] = realty;
                var announcement = new Announcement(inJson);
                return announcement;
            },
            loadData: function() {
                $.loadingBlock("loadAnnouncements", "show");
                var self = this;
                $.ajax({
                    type: "GET",
                    url: "<c:url value='/cabinet/api/getAnnouncements.json' />",
                    dataType : "json",
                    success: function (data, textStatus) {
                        console.log("in data:");
                        console.log(data);
                        for (var i in data) {
                            data[i] = self._getModel(data[i]);
                        }
                        self.add(data);
                        $.loadingBlock("loadAnnouncements", "hide");
                    } 
                });
            },
            comparator: function(inObj) {
                return parseInt(inObj.get('id'));
            },
            deleteAnnouncement: function(id) {
                var self = this;
                $.ajax({
                    type: "GET",
                    url: "<c:url value='/cabinet/api/deleteAnnouncement.json' />",
                    dataType : "json",
                    data: {id: id},
                    success: function (result, textStatus) {
                        if (result.error === false) {
                            self.remove([self.get(id)]);
                        } else {
                            alert(result.message);
                        }
                    } 
                });
            }
        });
        
        var AnnouncementView = Backbone.View.extend({
            initialize: function(){
                this.collection.bind("add", this.update, this);
                this.collection.bind("reset", this.update, this);
                this.collection.bind("remove", this.update, this);
            },
            _newRow: function(data) {
                return _.template($.getTemplate("announcementCabinetItem"), { announcement: data });
            },
            update: function() {
                this.$el.find("tbody").empty();
                for (var i in this.collection.models) {
                    this.$el.find("tbody").append(this._newRow(this.collection.models[i]));
                }
            }
        });
        
        announcementsController = new AnnouncementsController();
        announcementsCollection = new AnnouncementsCollection();
        announcementView = new AnnouncementView({
            collection: announcementsCollection,
            el: "#announcementsTable"
        });

    });
</script>
<div id="cabinetForm">
    <div class="pull-right"><a href="logout"><strong>Выйти</strong></a></div>
    <div>Здравствуйте, <strong><c:out value="${user.fullName}"/></strong></div>
    
    <div class="tabbable tabs-left" style="margin-top:20px;">
        <ul class="nav nav-tabs">
            <li class="active"><a href="#my_ads" data-toggle="tab">Мои обяъвления</a></li>
            <li><a href="#privat_info" data-toggle="tab">Личные данные</a></li>
            <li><a href="#additional" data-toggle="tab">Дополнительно</a></li>
        </ul>
        <div class="tab-content">
            <div class="tab-pane active" id="my_ads">
                <a class="btn btn-small" id="addAnnouncement" href="#newRealty">Добавить объявление</a>
                <div id="announcementsTable">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th></th>
                                <th>Статус</th>
                                <th>Тип</th>
                                <th style="width:150px">Адрес</th>
                                <th style="width:35px">Цена</th>
                                <th>Описание</th>
                                <th>Действие</th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>
            </div>
            <div class="tab-pane" id="privat_info">
                <table>
                   <tbody> 
                       <tr>
                           <td>ФИО</td>
                           <td><c:out value="${user.fullName}"/></td>  
                       </tr>
                       <tr>
                           <td>E-Mail</td>
                           <td><c:out value="${user.email}"/></td>                   
                       </tr>
                       <tr>
                           <td>Контактный телефон</td>
                           <td><c:if test="${user.telephoneNumber == null}">
                                   Не указан
                               </c:if>
                               <c:out value="${user.telephoneNumber}"/>
                           </td>
                       </tr>
                   </tbody>
                </table>
                <button class="btn btn-small" type="button">Изменить</button>
            </div>
            <div class="tab-pane" id="additional">
                <p>What up girl, this is Section C.</p>
            </div>
        </div>
    </div>
</div>                       
                               
<%@ include file="blocks/footer.jsp" %>
